# Direct outputs eligible for public release

# GLOBAL SETTINGS --------------------------------------------------------------

options(
  scipen = 999,
  digits = 16,
  max.print = .Machine$integer.max,
  show.error.locations = TRUE,
  warn = 1
)

RNGkind("L'Ecuyer-CMRG")
seed <- 818675309L
set.seed(seed) # setting main seed

# PACKAGES ---------------------------------------------------------------------

library(data.table)

# PACKAGE SETTINGS -------------------------------------------------------------

# data.table
setDTthreads(threads = 1)
options(datatable.print.class = TRUE, datatable.print.keys = TRUE)
# so that printing the data.table also shows the variable type on top

# BEGIN FILE -------------------------------------------------------------------

# Just in case something masks 'source()', use extra deliberate base::source().
base::source("~/code/0-utility-functions/table-and-text-utils.R", local = TRUE)

# READ IN OUR DATA -------------------------------------------------------------

# Focus on the aggregate (+1 to +5) estimates (event_time == 99) throughout

claim_oasi_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_has_ssinc_62_to_64.rds" #nolint
    )
setnames(claim_oasi_dt, "ref_event_time", "event_time")
claim_oasi_dt <- claim_oasi_dt[event_time == 99]

one_yr_exit_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_nonemployed_62_to_64.rds" #nolint
    )
setnames(one_yr_exit_dt, "ref_event_time", "event_time")
one_yr_exit_dt <- one_yr_exit_dt[event_time == 99]

two_yr_exit_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_two_years_nonemployed_62_to_64.rds" #nolint
    )
setnames(two_yr_exit_dt, "ref_event_time", "event_time")
two_yr_exit_dt <- two_yr_exit_dt[event_time == 99]

five_yr_exit_dt <-
    readRDS(
        "~/estimation-output/wealth_effect_estimates_five_years_nonemployed_62_to_64.rds" #nolint
    )
setnames(five_yr_exit_dt, "ref_event_time", "event_time")
five_yr_exit_dt <- five_yr_exit_dt[event_time == 99]

# MAKE TABLE -------------------------------------------------------------------

filedir <- "~/paper/tables/table-5.1.tex"
file.create(filedir)

# Start Table 5.1
start_latex_table(
    column_structure = "lcccccc",
    file_dir = filedir,
    append = TRUE
)
add_latex_table_rule(rule_type = "toprule", file_dir = filedir, append = TRUE)
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

heading_text_input1 <-
    " &  &  & \\multicolumn{4}{c}{Sample} "
write_latex_table_row(heading_text_input1, file_dir = filedir, append = TRUE)

add_latex_cmidrule(
    point_start_col = "l",
    point_end_col = "r",
    start_col = 4,
    end_col = 7,
    file_dir = filedir,
    append = TRUE
)

heading_text_input2 <-
    " \\multirow{3}{*}{Outcome} & \\multirow{3}{*}{Value} & & \\multirow{2}{*}{Full Sample} & & Quartile 1  &  Quartile 4 " #nolint
write_latex_table_row(heading_text_input2, file_dir = filedir, append = TRUE)

heading_text_input3 <-
    "  & & & & & Pre-Win Income  &  Pre-Win Income "
write_latex_table_row(heading_text_input3, file_dir = filedir, append = TRUE)

heading_text_input4 <-
    "  & & & (1) & & (2)  &  (3) "
write_latex_table_row(heading_text_input4, file_dir = filedir, append = TRUE)

heading_text_input1 <- NULL
heading_text_input2 <- NULL
heading_text_input3 <- NULL
heading_text_input4 <- NULL
rm(
    heading_text_input1,
    heading_text_input2,
    heading_text_input3,
    heading_text_input4
)

add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

# Add body of Table 5.1
# - introduce convenience functions given a similar structure throughout

Table51Row1 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            "\\multirow{4}{*}{%s} & Estimate & & %s & & %s & %s",
            text,
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

Table51Row2 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Standard Error & & (%s) & & (%s) & (%s)",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$cluster_se, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 4,
                decimal_digits = 4,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

Table51Row3 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Counterfactual Mean & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 2,
                decimal_digits = 2,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

Table51Row4 <- function(dt, text, scaler) {
    dt_temp <- copy(dt)
    dt_input <-
        sprintf(
            " & Percentage Change & & %s & & %s & %s",
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 5]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 5]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 1]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 1]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            ),
            fmt_fixed_decimal(
                input = dt_temp[model == "ratio" & income_quartile == 4]$estimate / dt_temp[model == "counterfactual_mean" & income_quartile == 4]$estimate, #nolint
                sub_for_missing = "-",
                should_be_rounded = TRUE,
                round_digits = 1,
                decimal_digits = 1,
                scale_factor = scaler,
                add_comma = TRUE
            )
        )
    write_latex_table_row(
        dt_input,
        file_dir = filedir,
        append = TRUE
    )
    invisible(dt_input)
}

# Claimed OASI
write_latex_table_row(
        "\\emph{Panel A: Take-Up of Retirement Benefits} & & & & & & ",
        file_dir = filedir,
        short_row_height = FALSE,
        append = TRUE
    )
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

Table51Row1(
    dt = claim_oasi_dt,
    text = "Claiming OASI Benefits",
    scaler = 100000
)
Table51Row2(
    dt = claim_oasi_dt,
    scaler = 100000
)
Table51Row3(
    dt = claim_oasi_dt,
    scaler = 1
)
Table51Row4(
    dt = claim_oasi_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )
add_latex_table_rule(rule_type = "midrule", file_dir = filedir, append = TRUE)

# Labor Market Exit
write_latex_table_row(
        "\\emph{Panel B: Labor Market Exit} & & & & & & ", #nolint
        file_dir = filedir,
        short_row_height = FALSE,
        append = TRUE
    )
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )
Table51Row1(
    dt = one_yr_exit_dt,
    text = "One-Year Exit",
    scaler = 100000
)
Table51Row2(
    dt = one_yr_exit_dt,
    scaler = 100000
)
Table51Row3(
    dt = one_yr_exit_dt,
    scaler = 1
)
Table51Row4(
    dt = one_yr_exit_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = FALSE,
        append = TRUE
    )
Table51Row1(
    dt = two_yr_exit_dt,
    text = "Two-Year Exit",
    scaler = 100000
)
Table51Row2(
    dt = two_yr_exit_dt,
    scaler = 100000
)
Table51Row3(
    dt = two_yr_exit_dt,
    scaler = 1
)
Table51Row4(
    dt = two_yr_exit_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = FALSE,
        append = TRUE
    )
Table51Row1(
    dt = five_yr_exit_dt,
    text = "Five-Year Exit",
    scaler = 100000
)
Table51Row2(
    dt = five_yr_exit_dt,
    scaler = 100000
)
Table51Row3(
    dt = five_yr_exit_dt,
    scaler = 1
)
Table51Row4(
    dt = five_yr_exit_dt,
    scaler = 10000000
)
write_latex_table_row(
        " & & & & & & ",
        file_dir = filedir,
        short_row_height = TRUE,
        append = TRUE
    )

# End Table 5.1
add_latex_table_rule(
  rule_type = "bottomrule",
  file_dir = filedir,
  append = TRUE
)
end_latex_table(file_dir = filedir, append = TRUE)
filedir <- NULL
rm(filedir)

# Housekeeping
claim_oasi_dt <- NULL
one_yr_exit_dt <- NULL
two_yr_exit_dt <- NULL
five_yr_exit_dt <- NULL
rm(claim_oasi_dt, one_yr_exit_dt, two_yr_exit_dt, five_yr_exit_dt)